<?php

namespace App\Channels;

use App\Models\SmsQueue;
use GuzzleHttp\Client;
use Illuminate\Notifications\Notification;

/**
 * 国博票务短信平台短信通知，容联云通讯
 *
 * @author lxp
 * @package App\Channels
 */
class GbpwSmsChannel
{
	/**
	 * 发送给定通知。
	 *
	 * @author lxp 20180720
	 * @param $notifiable
	 * @param Notification $notification
	 * @throws \GuzzleHttp\Exception\GuzzleException
	 */
	public function send($notifiable, Notification $notification)
	{
		// 取得短信模板id
		$sms_template_id = $notification->get_sms_template_id();
		// 取得短信模板参数
		$sms_parameter = $notification->get_sms_parameter($notifiable);
		// 取得手机号
		$mobile = null;
		if (method_exists($notifiable, 'mobileForSms')) {
			$mobile = $notifiable->mobileForSms();
		} elseif (method_exists($notification, 'get_mobile')) {
			$mobile = $notification->get_mobile();
		}

		if (is_mobile($mobile)) {
			// 加到短信发送队列
			/**
			 * $smsqueue = new SmsQueue();
			 * $smsqueue->send_class = 'GbpwSmsChannel';
			 * $smsqueue->sms_mobile = $mobile;
			 * $smsqueue->sms_template_id = $sms_template_id;
			 * $smsqueue->sms_parameter = serialize($sms_parameter);
			 * $smsqueue->save();
			 *
			 * try {
			 * // 异步处理短信队列
			 * (new Client())->get(url('sms_queue'), ['timeout' => 1]);
			 * } catch (\Exception $e) {
			 * }
			 **/

			// 直接发送短信
			self::sendSms($mobile, $sms_template_id, $sms_parameter);
		}
	}

	/**
	 * 发送短信
	 *
	 * @author lxp 20180504
	 * @param string $mobile 手机号
	 * @param int $sms_template_id 短信模板id
	 * @param array $sms_parameter 短信参数
	 * @return bool
	 * @throws \GuzzleHttp\Exception\GuzzleException
	 */
	public static function sendSms($mobile, $sms_template_id, $sms_parameter)
	{
		if (!is_mobile($mobile)) {
			return false;
		}

		$b_time = date('H:i:s');

		$dateNow = date('YmdHis');
		$accountSid = env('SMS_ACCOUNT_SID');
		$accountToken = env('SMS_ACCOUNT_TOKEN');
		$appId = env('SMS_APP_ID');
		$sigParameter = strtoupper(md5($accountSid . $accountToken . $dateNow));

		$client = new Client([
			'base_uri' => 'https://app.cloopen.com:8883',
			'timeout' => 8
		]);
		$request = $client->request('POST', "/2013-12-26/Accounts/{$accountSid}/SMS/TemplateSMS?sig={$sigParameter}", [
			'headers' => [
				'Accept' => 'application/json',
				'Content-Type' => 'application/json;charset=utf-8',
				'Authorization' => base64_encode("{$accountSid}:{$dateNow}")
			],
			'body' => json_encode([
				'to' => $mobile,
				'appId' => $appId,
				'templateId' => $sms_template_id,
				'datas' => $sms_parameter
			]),
			// 强制IPv4协议
			'force_ip_resolve' => 'v4'
		]);
		$result = $request->getBody()->getContents();

		$r_data = json_decode($result, true);
		if (is_array($r_data) && isset($r_data['statusCode']) && $r_data['statusCode'] == "000000") {
			// 记录短信发送日志
			$logObj = app('logext');
			$logObj->init('sms');
			$logObj->logbuffer('send_time', $b_time);
			$logObj->logbuffer('phone_no', $mobile);
			$logObj->logbuffer('content', $sms_parameter);
			$logObj->logbuffer('result', $r_data);
			$logObj->logend();

			return true;
		} else {
			$logObj = app('logext');
			$logObj->init('sms_error');
			$logObj->logbuffer('send_time', $b_time);
			$logObj->logbuffer('phone_no', $mobile);
			$logObj->logbuffer('content', $sms_parameter);
			$logObj->logbuffer('result', $r_data);
			$logObj->logend();

			return false;
		}
	}

}